package com.example.controller;



import cn.jiyun.config.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommomController {

    @Value("${reggie.path}")
    private String basePate;


    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //截取文件
        String substring = originalFilename.substring(originalFilename.indexOf("."));
        String fileName= UUID.randomUUID().toString()+substring;
        File dir=new File(this.basePate);
        //判断文件目录是否存在
        if (!dir.exists()){
            dir.mkdirs();//如果目录不存在，需要创建
        }
        try{
            file.transferTo(new File(this.basePate+fileName));

        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }



    @GetMapping("download")
    public void download(String name, HttpServletResponse response) throws IOException {
        try {
            File file = new File(basePate,name);
            FileInputStream fileInputStream = new FileInputStream(file);
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] buf=new byte[1024];
            int length=0;
            while ((length=fileInputStream.read(buf))!=-1){
                outputStream.write(buf,0,length);
            }
            fileInputStream.close();
        } catch (Exception e){
            e.printStackTrace();
        }

    }


}
